﻿using System.Runtime.CompilerServices;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;

namespace RayDen.Library.Data
{
    public class LatLongMap : EnvironmentSamplerBase, IEnvironmentMapSampler
    {
        private RgbSpectrumTexture tex;

        private RgbSpectrumTexture lightMap; 

        public string Name
        {
            get { return "LatLong_Envmap"; }
        }

        public string FileName
        {
            get { return tex.filePath; }
        }
        
        public LatLongMap(string path)
        {
            tex = LoadTexture(path);
        }

        public LatLongMap(RgbSpectrumTexture tex)
        {
            this.tex = tex;
        }

        public LatLongMap(RgbSpectrumTexture tex, RgbSpectrumTexture ltex)
        {
            this.tex = tex;
            this.lightMap = ltex;
        }

        public void Sample(ref Vector dir, out RgbSpectrumInfo outputColor)
        {
            var t = lightMap ?? tex;
            this.Sample(t, ref dir, out outputColor);
        }


        public void SampleBackground(ref Vector dir, out RgbSpectrumInfo outputColor)
        {
            Sample(tex, ref dir, out outputColor);
        }


        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private void Sample(RgbSpectrumTexture t, ref Vector dir, out RgbSpectrumInfo outputColor)
        {
            float shiftU = 0f, shiftV = 0f;
            float theta = Vector.SphericalTheta(ref dir);
            outputColor = t.Sample(Vector.SphericalPhi(ref dir) * MathLab.INVTWOPI + shiftU, theta * MathLab.INVPI + shiftV);
        }
    }
}